﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using CoreEx.Common.Data;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using LinFu.IoC;

namespace CoreEx.MicroMapper.Implementation
{
    [Implements(typeof(IMicroMapper<IDataReader, ITable>), ServiceName = "DataReaderToTableFactoryMapper")]
    public class DataReaderToTableFactoryMapper : MicroMapper<IDataReader,ITable>
    {
        public override void Initialize(IServiceContainer source)
        {
            base.Initialize(source);

            SourceAccessorSelector = (reader) =>
                                              {
                                                  IList<IAccessorInfo> accessorInfoList = new List<IAccessorInfo>(reader.FieldCount);
                                                   for (int i = 0; i < reader.FieldCount; i++)
                                                    {
                                                        var accessorInfo = source.GetService<IAccessorInfo>();
                                                        accessorInfo.Name = reader.GetName(i);
                                                        accessorInfo.DataType = reader.GetFieldType(i);
                                                        accessorInfoList.Add(accessorInfo);
                                                    }
                                                  return accessorInfoList;
                                              };
            
            
            SourceAccessor =
                ((accessorInfo, reader) =>
                     {
                         var column = source.GetService<IColumn>();
                         column.DataType = accessorInfo.DataType;
                         column.ColumnName = accessorInfo.Name;
                         return column;
                     });

            TargetAccessor =
                (accessorInfo, table, value) =>
                    {
                        ((IColumn) value).Table = table;
                        table.Columns.Add(((IColumn) value).ColumnName, (IColumn) value);
                    };


            

            TargetFactory = (s) => source.GetService<ITable>();
                        
        }
    }
}
